const os = require('os');
const express = require('express');
const cors = require('cors');
const QRCode = require('qrcode');
const si = require('systeminformation');

const app = express();

app.use(cors());

app.get('/systeminfo', async(req, res) => {
    try {
        const system = await si.system();
        const hostname = os.hostname();
        const boardSerial = system.serial;

        const hostnameQR = await QRCode.toDataURL(hostname, { errorCorrectionLevel: 'H' });
        const boardSerialQR = await QRCode.toDataURL(boardSerial, { errorCorrectionLevel: 'H' });

        res.json({
            hostname,
            boardSerial,
            hostnameQR,
            boardSerialQR
        });
    } catch (error) {
        console.error('Error fetching system information:', error);
        res.status(500).send('Error fetching system information');
    }
});

app.get('/macs', async(req, res) => {
    const interfaces = os.networkInterfaces();
    console.log('Network Interfaces:', interfaces); // 输出所有网络接口信息以便调试

    const results = [];

    for (const interfaceName in interfaces) {
        const iface = interfaces[interfaceName];

        for (const alias of iface) {
            if (!alias.internal) {
                const formattedMac = alias.mac.replace(/:/g, '-').toUpperCase();
                let qrCodeUrl = null;
                try {
                    qrCodeUrl = await QRCode.toDataURL(formattedMac, { errorCorrectionLevel: 'H' });
                } catch (err) {
                    console.error('Error generating QR code:', err);
                }

                results.push({
                    interface: interfaceName,
                    mac: formattedMac,
                    ip: alias.address || 'No IP Address',
                    qrCodeUrl
                });
            }
        }
    }

    if (results.length > 0) {
        res.json(results);
    } else {
        res.status(404).send('No valid MAC addresses found');
    }
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});